package javax.core.common.clazz;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

public class ClassUtils {

    public static Set<Class> scanJavaClassFromPackage(String rootPackage, boolean recursive) throws IOException {
        String packagePath = rootPackage.replace(".", "/");
        Set<Class> classSet = new HashSet<>();
        Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packagePath);
        while (dirs.hasMoreElements()) {
            URL url = dirs.nextElement();
            String protocol = url.getProtocol();
            // 如果是以文件的形式保存在服务器上
            if ("file".equals(protocol)) {
                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                parseClass(filePath, rootPackage, classSet);
            }
            if ("jar".equals(protocol)) {

            }

        }
        return classSet;
    }

    private static void parseClass(String filePath, String rootPackage, Set<Class> classSet) {
        File directory = new File(filePath);
        List<File> files = Arrays.asList(directory.listFiles());
        files.forEach(file -> {
            if (file.isDirectory()) {
                // it still is directory (package)
                parseClass(file.getPath() , rootPackage +"." + file.getName(), classSet);
            } else {
                String javaClassFile = rootPackage +"." + file.getName();
                if (javaClassFile.endsWith(".class")) { // must return as .class file
                    try {
                        classSet.add(Class.forName(javaClassFile.substring(0, javaClassFile.length() - 6)));
                    } catch (ClassNotFoundException e) {
                        System.err.println(e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
